package de.duester.genealogy.adapter;

import java.util.Comparator;
import java.util.List;

import de.duester.genealogy.R;
import de.duester.genealogy.model.Place;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class PlaceListAdapter extends ArrayAdapter<Place> implements Comparator<Place> {
	private Activity activity;
	private List<Place> places;

	public PlaceListAdapter(Context context, int textViewResourceId, List<Place> places) {
		super(context, textViewResourceId, places);
		activity = (Activity) context;
		this.places = places;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v;

		if (convertView == null) {
			LayoutInflater li = activity.getLayoutInflater();
			v = li.inflate(R.layout.place_list_element, null);
		} else
			v = convertView;

		TextView tvPlace = (TextView) v.findViewById(R.id.tvPlace);
		TextView tvParentPlace = (TextView) v.findViewById(R.id.tvParentPlace);

		tvPlace.setText(places.get(position).toString());

		Place parentPlace = places.get(position).getParent();
		if (parentPlace != null)
			tvParentPlace.setText(activity.getString(R.string.txtPlaceIn, parentPlace.toString()));

		v.setBackgroundResource(R.drawable.list_element);

		return v;
	}

	@Override
	public Place getItem(int position) {
		return places.get(position);
	}

	@Override
	public int compare(Place lhs, Place rhs) {
		return lhs.compare(rhs);
	}

}
